package com.ks.api.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(1)
public class IpAddressFilter implements Filter {

    @Value("${app.ip.whitelist:}")
    private String ipWhitelist;

    private List<String> allowedIps;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 如果配置了IP白名单，则拆分为列表
        if (ipWhitelist != null && !ipWhitelist.isEmpty()) {
            allowedIps = Arrays.asList(ipWhitelist.split(","));
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String ipAddress = getClientIpAddress(httpRequest);
        
        // 如果没有配置白名单或者IP在白名单内，则允许访问
        if (allowedIps == null || allowedIps.isEmpty() || allowedIps.contains(ipAddress)) {
            chain.doFilter(request, response);
        } else {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
            httpResponse.getWriter().write("Access denied: IP " + ipAddress + " is not allowed");
        }
    }

    @Override
    public void destroy() {
        // 不需要实现
    }
    
    // 获取客户端真实IP地址
    private String getClientIpAddress(HttpServletRequest request) {
        String xForwardedForHeader = request.getHeader("X-Forwarded-For");
        if (xForwardedForHeader != null) {
            // 取第一个IP，即真实客户端IP
            return xForwardedForHeader.split(",")[0].trim();
        }
        
        String remoteAddr = request.getRemoteAddr();
        // 如果是本地测试，则返回环回地址
        if ("0:0:0:0:0:0:0:1".equals(remoteAddr)) {
            return "127.0.0.1";
        }
        
        return remoteAddr;
    }
} 